package com.semicolon_dtn_student;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.File;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Calendar;
import java.util.List;

import android.app.*;
import android.content.*;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.*;
import android.util.Log;
import android.view.*;
import android.widget.*;

public class manualmenu extends Activity {
	/** Called when the activity is first created. */

	WifiManager wifimanager;
	private List<ScanResult> mScanResults;
	TextView scanResultText;
	EditText IPAddress;
	ImageView image;
	int scancount = 0;
	Bitmap bitmap;
	Bitmap bitmapin;
	EditText input_file_select;
	Button button_file_select;
	TextView text_file_name;
	public String filename;
	public String filenamesv;

	String selected_filename;
	
	

	/* Information of Network */
	public static final int port = 8000;
	// public static final String broadcastIP = "193.168.0.255";
	public static final String broadcastIP = "193.168.0.2";
	public String msg = "DTN";


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.manualmenu);

		scanResultText = (TextView) findViewById(R.id.scanResultText);

		wifimanager = (WifiManager) getSystemService(WIFI_SERVICE);
		if (wifimanager.isWifiEnabled() == false) {
			wifimanager.setWifiEnabled(true);
			printToast("Wifi state is changed to Enable");
		}

	}

	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
				printScanResult();
				wifimanager.startScan();
				// mListAdapter.notifyDataSetChanged();

			} else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
				sendBroadcast(new Intent("wifi.ON_NETWORK_STATE_CHANGED"));
			}
		}
	};

	
	public void printToast(String messageToast) {
		Toast.makeText(this, messageToast, Toast.LENGTH_SHORT).show();
	}

	public void printScanResult() {
		mScanResults = wifimanager.getScanResults();
		scanResultText.setText("");
		scancount = scancount + 1;
		scanResultText.append("Scan Count : " + scancount + "\n");
		scanResultText.append("================================\n");

		for (int i = 0; i < mScanResults.size(); i++) {
			ScanResult result = mScanResults.get(i);

			
				scanResultText.append("ADHOC - " + (i + 1) + ".BSSID: "
						+ result.BSSID.toString() + "\t\t RSSI : "
						+ result.level + " dBm\n" + "\t\t SSID : "
						+ result.SSID.toString() + "\t\t Frequency : " 
						+ result.frequency+ " GHz\n");
			

		}

		scanResultText.append("================================\n");

	}

	private boolean isAdHoc(final ScanResult scanResult) {
		return scanResult.capabilities.indexOf("IBSS") != -1;
	}

	public void su(View v) {
		try {
			Runtime runtime = Runtime.getRuntime();
			java.lang.Process process;
			
			process = runtime.exec(new String[] {"su", "-c", "iwconfig eth0 mode ad-hoc essid MnetAdhoc"});
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void scanAdhoc(View v) {
		final IntentFilter filter = new IntentFilter(
				WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
		filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
		registerReceiver(mReceiver, filter);
		wifimanager.startScan();
		printToast("Scanning");
	}

	public void startClient(View v) {
		Thread UDPClinetThread = new UDPClientThread();
		UDPClinetThread.setDaemon(true);
		UDPClinetThread.start();
		printToast("Start Broadcasting");
	}

	public void stopClient(View v) {

		printToast("Stop Broadcasting");
	}

	public void stopScan(View v) {
		unregisterReceiver(mReceiver);
		printToast("Stop Scanning");

	}

	/* UDP Network code */

	class UDPClientThread extends Thread {
		DatagramSocket socket;
		DatagramPacket outPacket;
		

		public void run() {

			try {
				Log.d("Client", "Thread Starting...");
				socket = new DatagramSocket();
				Log.d("Client", "Socket Creating...");
				InetAddress broadcastAddr = InetAddress.getByName(broadcastIP);

				byte[] buf = new byte[128];
			
				Calendar c = Calendar.getInstance();
				int year = c.get(Calendar.YEAR);
				int month = c.get(Calendar.MONTH);
				int day = c.get(Calendar.DAY_OF_YEAR);
				
				int day_percent = ConstantVal.calculateDayPercent(year, month, day);
				String day_percent_string = ""+day_percent;
				buf = day_percent_string.getBytes();
										
				outPacket = new DatagramPacket(buf, buf.length, broadcastAddr,
						port);			
				
				Log.d("Client", "Out Packet Making...");

				socket.send(outPacket);
				Log.d("Client", "Broadcasting Starting end...");
								
				socket.close();
				Log.d("Client", "socket close...");
				

			} catch (SocketException e) {
				Log.d("Client", "SocketError");
				e.printStackTrace();
			} /*
			 * catch (InterruptedException e) { Log.d("Client","IOError");
			 * e.printStackTrace(); }
			 */catch (IOException e) {
				Log.d("Client", "InterruptError");
				e.printStackTrace();
			}
		}

	}
}
